package worker

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	rlog "recorder/log"
)

type LogWriter struct {
	logger *log.Logger
}

func NewLogWriter(jobId string, path string) *LogWriter {
	logFilePathName := filepath.Join(path, fmt.Sprintf("%v.log", jobId))
	rlog.Info("%s: begin NewLogWriter", jobId)
	os.MkdirAll(filepath.Dir(logFilePathName), os.ModePerm)
	file, err := os.OpenFile(logFilePathName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, os.ModePerm)
	if err != nil {
		rlog.Error("job %s open log err: %v", jobId, err)
		return nil
	}
	logger := log.New(file, "", log.Ldate|log.Ltime|log.Lmicroseconds)
	return &LogWriter{
		logger: logger,
	}
}

func (l *LogWriter) Write(buf []byte) (int, error) {
	l.logger.Print(string(buf))
	return len(buf), nil
}
